import { Button, Card, Col, List, message, Modal, Row, Tag, Typography } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar, GridContent } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { queryRule, removeRule, getMonitorOfChartInfo } from './service';
import LineNameChart from './components/LineNameChart';
import './monitor.less';

/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      idList: selectedRows.map((row) => row.id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const ListItem = List.Item;
  const actionRef = useRef();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const [clickRowsValue, setClickRows] = useState({});
  const [chartModalVisible, setChartModalVisible] = useState(false);
  const [accestsloading, setAccestsloading] = useState(false);
  const [productNamePieData, setProductNamePieData] = useState([]);
  const [clientAppIdPieData, setClientAppIdPieData] = useState([]);
  const [reqCostBarData, setReqCostBarData] = useState([]);
  const [reqTimeBarData, setReqTimeBarData] = useState([]);

  useEffect(() => {
    setAccestsloading(true);
    getMonitorOfChartInfo().then((res) => {
      if (res.status === 200) {
        setAccestsloading(false);
        getProductNamePieData(res.data.productname);
        getClientAppIdPieData(res.data.clientappid);
        getReqCostBarData(res.data.reqcost);
        getReqTimeBarData(
          res.data.reqtimeOne,
          res.data.reqtimeTwo,
          res.data.reqtimeThree,
          res.data.reqtimeFour,
        );
      }
    });
  }, []);

  function getProductNamePieData(data) {
    const chartData = {};
    const charts = [];
    const lineNames = [];
    const sizes = [];
    // eslint-disable-next-line no-restricted-syntax
    let count = 0;
    // eslint-disable-next-line guard-for-in,no-restricted-syntax
    for (const xyi in data) {
      count += data[xyi].size;
      lineNames.push(data[xyi].lineName);
      sizes.push(data[xyi].size);
      charts.push({
        name: data[xyi].lineName,
        value: data[xyi].size,
      });
    }
    chartData.productNameTotal = count;
    chartData.clientAppIds = lineNames;
    chartData.sizes = sizes;
    chartData.charts = charts;
    setProductNamePieData(chartData);
  }
  function getClientAppIdPieData(data) {
    const chartData = {};
    const charts = [];
    const clientAppIds = [];
    const sizes = [];
    // eslint-disable-next-line no-restricted-syntax
    let count = 0;
    // eslint-disable-next-line guard-for-in,no-restricted-syntax
    for (const xyi in data) {
      count += data[xyi].size;
      clientAppIds.push(data[xyi].clientAppId);
      sizes.push(data[xyi].size);
      charts.push({
        name: data[xyi].clientAppId,
        value: data[xyi].size,
      });
    }
    chartData.clientAppIdTotal = count;
    chartData.clientAppIds = clientAppIds;
    chartData.sizes = sizes;
    chartData.charts = charts;
    setClientAppIdPieData(chartData);
  }
  function getReqCostBarData(data) {
    const chartData = {};
    const charts = [];
    const reqCosts = [];
    const sizes = [];
    // eslint-disable-next-line no-restricted-syntax
    let count = 0;
    // eslint-disable-next-line guard-for-in,no-restricted-syntax
    for (const xyi in data) {
      if (data[xyi].reqCost === '0-500') {
        // eslint-disable-next-line no-param-reassign
        data[xyi].reqCost = '0-500ms';
      } else if (data[xyi].reqCost === '500-1000') {
        // eslint-disable-next-line no-param-reassign
        data[xyi].reqCost = '500-1000ms';
      } else if (data[xyi].reqCost === '1000-2000') {
        // eslint-disable-next-line no-param-reassign
        data[xyi].reqCost = '1000-2000ms';
      } else if (data[xyi].reqCost === '2000-3000') {
        // eslint-disable-next-line no-param-reassign
        data[xyi].reqCost = '2000-3000ms';
      } else if (data[xyi].reqCost === '3000-4000') {
        // eslint-disable-next-line no-param-reassign
        data[xyi].reqCost = '3000-4000ms';
      } else if (data[xyi].reqCost === '4000-5000') {
        // eslint-disable-next-line no-param-reassign
        data[xyi].reqCost = '4000-5000ms';
      } else if (data[xyi].reqCost === '5000-') {
        // eslint-disable-next-line no-param-reassign
        data[xyi].reqCost = '5000ms以上';
      }
      count += data[xyi].size;
      reqCosts.push(data[xyi].reqCost);
      sizes.push(data[xyi].size);
      charts.push({
        name: data[xyi].reqCost,
        value: data[xyi].size,
      });
      chartData.count = count;
      chartData.charts = charts;
      chartData.reqCosts = reqCosts;
      chartData.sizes = sizes;
    }
    setReqCostBarData(chartData);
  }
  function getReqTimeBarData(reqtimeOne, reqtimeTwo, reqtimeThree, reqtimeFour) {
    const chartData = {};
    const charts = [];
    const reqTimes = ['0点-6点', '6点-12点', '12点-18点', '18点-24点'];
    const reqTimeTypes = ['耗时告警', '健康检查告警', '后台服务告警'];
    const reqTimeCosts = [];
    const reqTimeHealths = [];
    const reqTimeServers = [];
    // eslint-disable-next-line guard-for-in,no-restricted-syntax
    for (const xyi in reqtimeOne) {
      if (reqtimeOne[xyi].alarmType === '耗时告警') {
        reqTimeCosts[0] = reqtimeOne[xyi].size;
      } else if (reqtimeOne[xyi].alarmType === '健康检查告警') {
        reqTimeHealths[0] = reqtimeOne[xyi].size;
      } else if (reqtimeOne[xyi].alarmType === '后台服务告警') {
        reqTimeServers[0] = reqtimeOne[xyi].size;
      }
    }
    // eslint-disable-next-line no-restricted-syntax
    for (const xyi in reqtimeTwo) {
      if (reqtimeTwo[xyi].alarmType === '耗时告警') {
        reqTimeCosts[1] = reqtimeTwo[xyi].size;
      } else if (reqtimeTwo[xyi].alarmType === '健康检查告警') {
        reqTimeHealths[1] = reqtimeTwo[xyi].size;
      } else if (reqtimeTwo[xyi].alarmType === '后台服务告警') {
        reqTimeServers[1] = reqtimeTwo[xyi].size;
      }
    }
    // eslint-disable-next-line no-restricted-syntax
    for (const xyi in reqtimeThree) {
      if (reqtimeThree[xyi].alarmType === '耗时告警') {
        reqTimeCosts[2] = reqtimeThree[xyi].size;
      } else if (reqtimeThree[xyi].alarmType === '健康检查告警') {
        reqTimeHealths[2] = reqtimeThree[xyi].size;
      } else if (reqtimeThree[xyi].alarmType === '后台服务告警') {
        reqTimeServers[2] = reqtimeThree[xyi].size;
      }
    }
    // eslint-disable-next-line no-restricted-syntax
    for (const xyi in reqtimeFour) {
      if (reqtimeFour[xyi].alarmType === '耗时告警') {
        reqTimeCosts[3] = reqtimeFour[xyi].size;
      } else if (reqtimeFour[xyi].alarmType === '健康检查告警') {
        reqTimeHealths[3] = reqtimeFour[xyi].size;
      } else if (reqtimeFour[xyi].alarmType === '后台服务告警') {
        reqTimeServers[3] = reqtimeFour[xyi].size;
      }
    }
    chartData.charts = charts;
    chartData.reqTimes = reqTimes;
    chartData.reqTimeTypes = reqTimeTypes;
    chartData.reqTimeCosts = reqTimeCosts;
    chartData.reqTimeHealths = reqTimeHealths;
    chartData.reqTimeServers = reqTimeServers;
    setReqTimeBarData(chartData);
  }

  const columns = [
    {
      title: '事件ID',
      dataIndex: 'id',
      key: 'id',
      sorter: true,
    },
    {
      title: '产线名称',
      key: 'lineName',
      dataIndex: 'lineName',
    },
    {
      title: '告警类型',
      key: 'alarmType',
      dataIndex: 'alarmType',
    },
    {
      title: '客户AppId',
      key: 'clientAppId',
      dataIndex: 'clientAppId',
    },
    {
      title: '请求耗时',
      key: 'expendTime',
      dataIndex: 'expendTime',
    },
    {
      title: '告警状态',
      key: 'sendWeixinFlag',
      dataIndex: 'sendWeixinFlag',
      hideInForm: true,
      render: (text, record) => {
        const color = record.sendWeixinFlag === '1' ? 'red' : 'green';
        return (
          <Tag color={color} key={record.sendWeixinFlag}>
            {text === '1' ? '发送异常' : '已发送'}
          </Tag>
        );
      },
    },
    {
      title: '告警时间',
      key: 'createTime',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
    },
  ];

  return (
    <PageContainer>
      <GridContent>
        <Row gutter={24}>
          <Col lg={17} md={24}>
            <ProTable
              headerTitle="查询表格"
              actionRef={actionRef}
              rowKey="key"
              request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
              columns={columns}
              rowSelection={{
                onChange: (_, selectedRows) => setSelectedRows(selectedRows),
              }}
              onRow={(record) => {
                return {
                  onClick: () => {
                    setClickRows(record);
                  },
                };
              }}
              toolBarRender={() => [
                <Button type="primary" onClick={() => setChartModalVisible(true)}>
                  查看图表
                </Button>,
              ]}
            />
            {chartModalVisible ? (
              <Modal
                className={'monitorSty'}
                width={1300}
                height={800}
                destroyOnClose
                confirmLoading={false}
                onCancel={() => setChartModalVisible(false)}
                cancelText="关闭"
                footer={[]}
                title={
                  <div
                    style={{
                      width: '100%',
                    }}
                  >
                    耗时监控报表
                  </div>
                }
                visible={chartModalVisible}
              >
                <LineNameChart
                  loading={accestsloading}
                  productNamePieData={productNamePieData}
                  clientAppIdPieData={clientAppIdPieData}
                  reqCostBarData={reqCostBarData}
                  reqTimeBarData={reqTimeBarData}
                />
              </Modal>
            ) : null}
            {selectedRowsState?.length > 0 && (
              <FooterToolbar
                extra={
                  <div>
                    已选择{' '}
                    <a
                      style={{
                        fontWeight: 600,
                      }}
                    >
                      {selectedRowsState.length}
                    </a>{' '}
                    项
                  </div>
                }
              >
                <Button
                  type="primary"
                  danger
                  onClick={async () => {
                    await handleRemove(selectedRowsState);
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest();
                  }}
                >
                  批量删除
                </Button>
              </FooterToolbar>
            )}
          </Col>
          <Col lg={7} md={24}>
            <Card
              title="告警详情"
              headStyle={{ textAlign: 'center', fontWeight: 'bold', borderBottomColor: '#e0dddd' }}
              style={{ backgroundColor: '#e6f7ffe3' }}
            >
              <List itemLayout="horizontal" size="large">
                <ListItem>
                  <Typography.Text>产线名称：</Typography.Text>{' '}
                  <span>{clickRowsValue.lineName}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>告警类型：</Typography.Text>{' '}
                  <span>{clickRowsValue.alarmType}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>业务AppId：</Typography.Text> <span>{clickRowsValue.appId}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>业务AppKey：</Typography.Text>{' '}
                  <span>{clickRowsValue.appKey}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>客户AppId：</Typography.Text>{' '}
                  <span>{clickRowsValue.clientAppId}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>请求时间：</Typography.Text>{' '}
                  <span>{clickRowsValue.requestTime}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>请求耗时：</Typography.Text>{' '}
                  <span>{clickRowsValue.expendTime}</span>
                </ListItem>
                <ListItem>
                  <Typography.Text>告警状态：</Typography.Text>{' '}
                  {
                    // eslint-disable-next-line no-nested-ternary
                    clickRowsValue.sendWeixinFlag === '0' ? (
                      <span>已发送</span>
                    ) : clickRowsValue.sendWeixinFlag === '1' ? (
                      <span>发送异常</span>
                    ) : (
                      <span />
                    )
                  }
                </ListItem>
                <ListItem>
                  <Typography.Text>请求结果：</Typography.Text>{' '}
                  <span>{clickRowsValue.clientRequestResult}</span>
                </ListItem>
              </List>
            </Card>
          </Col>
        </Row>
      </GridContent>
    </PageContainer>
  );
};

export default TableList;
